package com.uh.microservice.core.util;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.JacksonXmlModule;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import org.apache.commons.lang.StringUtils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;


/**
 * Created by liming on 2017/9/15.
 */
public class JSONParser {
    public static List json2List(String JSON){
        ObjectMapper obm=new ObjectMapper();
        List list=null;
        try {
            list=obm.readValue(JSON,List.class);
        } catch (Exception e) {
            return null;
        }
        return list;
    }

    public static Map xml2Map(String xml){
        try{
            JacksonXmlModule jacksonXmlModule = new JacksonXmlModule();
            jacksonXmlModule.setDefaultUseWrapper(false);

            XmlMapper xmlMapper = new XmlMapper(jacksonXmlModule);
            return xmlMapper.readValue(xml,Map.class);
//            JsonNode node = xmlMapper.readTree(xml.getBytes());
//            ObjectMapper jsonMapper = new ObjectMapper();
//            String json = jsonMapper.writeValueAsString(node);
//            return JSONParser.json2Map(json);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public static Map json2Map(String json){
        ObjectMapper obm=new ObjectMapper();
        Map list=null;
        try {
            // json 为空返回null
            if(StringUtils.isBlank(json)){
                return list;
            }
            list=obm.readValue(json,Map.class);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return list;
    }

    public static String obj2Json(Object obj){
        ObjectMapper obm = new ObjectMapper();
        try{
            DateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            obm.setDateFormat(dateFormat);
            return obm.writeValueAsString(obj);
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }
    }

    public static Object json2Obj(String json){
        ObjectMapper obm=new ObjectMapper();
        try {
            if(StringUtils.isBlank(json)){
                return null;
            }
            return obm.readValue(json,Object.class);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
